#coding=utf-8
'''
Created on 2011-2-23

@author: zarra
'''
import json
from model.drug_post import drug,Drug_Post
from model.expr_a import expr_a,Bcjl,Ryjl

class TreeNode(object):
    def __init__(self,id,text,*args,**argw):
        self.id=id
        self.text=text
        self.keys = argw.keys()
        for key in argw.keys():
            setattr(self, key, argw[key])
        self.items=[]
        if len(args) > 0:
            for a in args:
                if isinstance(a, TreeNode):
                    self.items.append(a)
                else:
                    items = []
                    try:
                        items = a['items']
                    except KeyError:pass
                    self.items.append( TreeNode(a['id'],a['text'],*items) )
            
    def __json__(self):
        if len(self.items) >0:
            leaf = False
        else:
            leaf = True
        result =  {'id':self.id,'text':self.text,'leaf':leaf}
        for key in self.keys:
            result[key]=getattr(self, key)
        return result
    def __repr__(self):
        return json.dumps(self.__json__())
    def find_child_by_id(self,id):
        if self.id == id:
            return self
        for i in self.items:
                r = i.find_child_by_id(id)
                if r != None:
                    return r
        return None
    

class Tree(object):
    def __init__(self,root):
        self.root = root           
    def get_tree(self,*args):
        id=args[0]
        node = self.root.find_child_by_id(id)
        if node != None:
            return node.items
        
        
class Drug_post_Tree(Tree):
    def __init__(self,root):
        super(Drug_post_Tree,self).__init__(root)
    def get_tree(self,pid,nid):
        if len(pid) == 0:
            return []       
        s=drug()
        children_record = s.query(Drug_Post).filter(Drug_Post.patient_id == pid).all()
        items=[]
        for record in children_record:
            items.append(TreeNode(str(record.id),\
                                  str(record.last_modify_time),\
                                   action='load_drug_post(%s)'%record.id));
        s.close()
        items.append(TreeNode('drug_add','增加',action='new_drug_post()'));
        return items
        
        
class BL_Tree(Tree):
    def __init__(self,root):
        super(BL_Tree,self).__init__(root)
    def get_tree(self,pid,nid):
            s=expr_a()
            result =s.query(Bcjl).filter(Bcjl.bl_id == '1400000922').first()
            print result

                
    
if __name__ == '__main__':
    root = TreeNode('root','root',{'id':'child','text':'child'});
    tree = BL_Tree(root)
    tree.get_tree(0, 0)
        